// pages/shopping/shoppingHome/shoppingHome.js
var app = getApp();
var _PAGESIZE = 12;
var util = require("../../../utils/util.js");
var QQMapWX = require('../../../libs/qqmap-wx-jssdk.js');
var MapWXsap = new QQMapWX({
  key: '3VPBZ-KJ5LQ-7Y55U-GZ6HH-BJ2XH-RBB6B' // 必填
});
var zllc = app.globalData._network_path + 'rental_process.png';
// ak_code: 'nwq7az2Kl6W4if8u13p3ikMqC9wd6uVe',//百度地图key
// ak_code: '3VPBZ-KJ5LQ-7Y55U-GZ6HH-BJ2XH-RBB6B',//腾讯地图key
var load= true;
var address_component= { };
var area_id_Info= []; //选中的地区id信息
var codeInfo= '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    icon: '../../../images/position_s.png', //定位图标地址
    hot_icon: '../../../images/hot_icon.png', //定位图标地址
    new_icon: '../../../images/new_icon.png', //定位图标地址
    imgUrls: [], //banner图
    indicatorDots: true, //是否示面板指示点
    autoplay: true, //是否自动切换
    interval: 3000, //自动切换时间间隔
    indicatorColor: '#fff', //指示点颜色
    indicatorActiveColor: '#004bb7', //当前选中的指示点颜色
    current: 0, //当前所在滑块的 index
    goods: [],
    animation: {},
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value_sel: [0, 0, 0], //对应数组下标
    value: [9999, 1, 1], //默认下标
    province_s: [],
    city_s: [],
    area_s: [],
    areaInfo_name: [], //选中地区名称
    province: '',
    city: '',
    area: '',
    hasMore: false, //数据是否加载完成
    loading: false,
    load_show: false,
    isLoacation: false, //是否授权地址
    showFlag: false,
    latitude: '',
    longitude: '',
    isSelectCity: false, //是否选择地址
    tdsinfo: 0,
    page: 1,
    zllc: zllc ,//流程图
    is_change:false,
    onTab:0,
    tablelist: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    that.getEquipmentstypeList();//获取table列表 table切换列表

  },
  //获取用户授权信息并且查询商品列表
  getUserAuthInfo(){
    var that = this;
    //获取本地信息
    that.setData({
      goods: [],
      load_show: false,
      page: 1
    });
    load=true;
    var is_chan_ge = wx.getStorageSync('is_change');
    var latlength = wx.getStorageSync('lat');
    var tiMore = wx.getStorageSync('tiMore') ? wx.getStorageSync('tiMore') : 1;
    var lnglength = wx.getStorageSync('lng');
    var area_arr_id = wx.getStorageSync('area_id');
    var area_arr_name = wx.getStorageSync('areaInfo_name');
    if (is_chan_ge) {
      that.setData({
        areaInfo_name: area_arr_name
      })
      area_id_Info= area_arr_id
    }
    if (area_arr_id.length != 0 && area_arr_name.length != 0 && tiMore >= 3 && latlength == '' && is_chan_ge) {
      that.setData({
        areaInfo_name: area_arr_name
      })
      area_id_Info = area_arr_id
      that.getGoodsList();//获取列表
      //更新地址
      if (wx.getStorageSync('phone')) {
        that.updateTwoAddress(area_arr_name);
      }
      return
    } else {
      if (latlength != '' || tiMore == undefined || tiMore < 3) {
        that.get_location();
      } else if (tiMore >= 3 && !is_chan_ge && latlength == '') {
        wx.navigateTo({
          url: '../../setPosition/setPosition?mytab=true',
        })
      }
    }
    if (tiMore == 1 || tiMore == undefined || tiMore == '') {
      wx.setStorageSync("tiMore", 2);
    } else if (tiMore == 2) {
      wx.setStorageSync("tiMore", 3);
      wx.setStorageSync('is_change', false);
    }
    that.getBannerList(); // 获取广告数据
  },
  //修改手机号码
  changeAdd(){
    var that=this;
    if (wx.getStorageSync('tiMore')>=3){
      wx.setStorageSync("tiMore", 1);
      // wx.setStorageSync('is_change', false);
    }
    that.get_location();
    // wx.navigateTo({
    //   url: '../../setPosition/setPosition?mytab=true',
    // })
  },
  //是否授权位置
  get_location() {
    var that = this;
    wx.getLocation({
      success: function (res) {
        wx.setStorageSync('lat', res.latitude);
        wx.setStorageSync('lng', res.longitude);
        that.getCityLocation(res.latitude, res.longitude);
        app.showToast('定位中...')
      },
      fail: function (res) {
        const version = wx.getSystemInfoSync().SDKVersion;
        var area_arr_id = wx.getStorageSync('area_id');
        var area_arr_name = wx.getStorageSync('areaInfo_name');
  
        if (that.compareVersion(version, '2.3.2') < 0) {
          // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
          wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用部分功能，请升级到最新微信版本后重试。'
          })
          return false;
        }
        app.showModal("", "需要地理位置定位,请先授权", function () {
          wx.openSetting({
            success(res) {
              if (res.authSetting['scope.userLocation'] == true) {
                // that.position();
              }
            }
          })
        }, function () {

        });
      }
    })
  },
  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }
    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])

      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }

    return 0
  },

  // 获取广告banner
  getBannerList() {
    var that = this;
    // ajax请求
    app.ajax({
      url: 'Common/Banner/getBannerList',
      data: {
        'type': 2
      },
      success: function(res) {
        if (res.data.code == 1000) {
          that.setData({
            imgUrls: res.data.data
          })
        }
        //console.log('广告信息',res);
        that.shareLogHistory();//浏览记录
      }
    })
  },
  // 获取当前位置
  getLocation: function() {
    var that = this;
    wx.getLocation({
      success: function(res) {
        that.setData({
          isLoacation: true,
          showFlag: false,
          latitude: res.latitude,
          longitude: res.longitude,
        });
        wx.setStorageSync('lat', res.latitude);
        wx.setStorageSync('lng', res.longitude);
        that.getCityLocation(res.latitude, res.longitude);
        
      },
      fail: function(res) {
        var area_id = wx.getStorageSync('area_id');
        var isSelectCity = false;
        if (area_id.length > 0) {
          isSelectCity = true;
        }
        console.log(isSelectCity);
        that.setData({
          isLoacation: false,
          showFlag: true,
          isSelectCity: isSelectCity
        });
        // wx.hideLoading();
        wx.showToast({
          title: '获取经纬度失败',
          icon: 'none',
          duration: 1000
        })
      }
    })
  },

  // 再次获取位置
  handler: function(e) {
    var that = this;
    if (e.detail.authSetting["scope.userLocation"]) {
      //如果打开了地理位置，就会为true
      this.setData({
        isLoacation: true,
        showFlag: false
      });
      that.getLocation();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var that = this;
    //console.log(1222);
    // wx.removeStorageSync('area_id');
    // wx.removeStorageSync('areaInfo_name');
    that.setData({
      goods: [],
      load_show: false,
      page:1,
    });
    wx.showLoading({
      title: '加载中...'
    });
    that.getGoodsList();
   // that.getLocation();
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    var hasMore = that.data.hasMore;
    if (!hasMore) {
      return false;
    }
    var page = that.data.page + 1;
    taht.setData({
      page: page
    })

    that.setData({
      loading: true
    })
    that.getGoodsList();
  },


  /**
   * 幻灯片切换
   */
  bindChange: function(e) {
    //console.log(e.detail.current);
    // this.setData({
    //   current : e.detail.current
    // })
  },
  // 点击所在地区弹出选择框
  selectDistrict: function(e) {
    var that = this
    if (!that.data.isLoacation && !that.data.isSelectCity) {
      wx.hideTabBar();
      that.getProvince(); //获取省份信息
      if (that.data.addressMenuIsShow) {
        return
      }
      that.startAddressAnimation(true)
    } else {
      app.showToast('已选择地址，不能修改');
    }

  },
  // 执行动画
  startAddressAnimation: function(isShow) {
    var that = this
    if (isShow) {
      that.animation.translateY(0 + 'vh').step()
    } else {
      that.animation.translateY(60 + 'vh').step()
    }
    that.setData({
      animationAddressMenu: that.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  // 点击地区选择取消按钮
  cityCancel: function(e) {
    var that = this;
    wx.showTabBar();
    that.startAddressAnimation(false);
    that.setProDefault(codeInfo);
  },
  // 点击地区选择确定按钮
  citySure: function(e) {
    var that = this
    wx.showModal({
      title: '提示',
      content: '选择地址后不可修改',
      success(res) {
        if (res.confirm) {
          var value_sel = that.data.value_sel;
          that.startAddressAnimation(false)
          // 将选择的城市信息放入数组后期方便操作
          var areaInfo_name = []; //区域名称
          areaInfo_name.push(that.data.province_s[value_sel[0]].area_name);
          areaInfo_name.push(that.data.city_s[value_sel[1]].area_name);
          areaInfo_name.push(that.data.area_s[value_sel[2]].area_name);
          var area_id_Info_s = []; //区域id
          area_id_Info_s.push(that.data.province_s[value_sel[0]].id);
          area_id_Info_s.push(that.data.city_s[value_sel[1]].id);
          area_id_Info_s.push(that.data.area_s[value_sel[2]].id);
          wx.setStorage({
            key: 'area_id',
            data: area_id_Info_s,
          });
          wx.setStorage({
            key: 'areaInfo_name',
            data: areaInfo_name
          });
          //console.log(area_id_Info);
          area_id_Info = area_id_Info_s;
          that.setData({
            areaInfo_name: areaInfo_name,
            hasMore: false, //数据是否加载完成
            loading: false,
            load_show: false,
            goods: [],
            isLoacation: false,
            showFlag: false,
            page: 1
          })
          load= true;
          that.getGoodsList();
        } else if (res.cancel) {
          //console.log('用户点击取消')
        }
        wx.showTabBar();

      }
    })
  },
  //点击黑色区域关闭地址选择
  hideCitySelected: function(e) {
    var that = this;
    //console.log('black**************');
    wx.showTabBar();
    that.startAddressAnimation(false);
    that.setProDefault(codeInfo);
  },
  // 处理省市县联动逻辑
  cityChange: function(e) {
    var that = this;
    var value_sel = e.detail.value; //获取选中的id数组
    // console.log(value_sel);
    var provinces = this.data.provinces
    var citys = this.data.citys
    var areas = this.data.areas
    var province_Num = value_sel[0]
    var city_Num = value_sel[1]
    var county_Num = value_sel[2]
    //判断是否需要切换市区级
    if (this.data.value_sel[0] != province_Num) {
      var provinceid = that.data.province_s[province_Num].id; //获取省id查询市级信息
      that.getCity(provinceid); //获取市级信息
      this.setData({
        value_sel: [province_Num, 0, 0],
      })
    } else if (this.data.value_sel[1] != city_Num) { //判断是否需要切换区域
      var cityid = that.data.city_s[city_Num].id;
      that.getArea(cityid); //获取区域信息
      this.setData({
        value_sel: [province_Num, city_Num, 0],
      })
    } else {
      this.setData({
        value_sel: [province_Num, city_Num, county_Num]
      })
    }
  },
  //获取省级信息 getProvince
  getProvince: function() {
    var that = this;
    app.ajax({
      url: 'Common/Areas/areas',
      method: "POST",
      data: {
        parent_id: 0
      },
      success: function(res) {
        if (res.data.code == 1000) {
          that.setData({
            province_s: res.data.data
          })
          //初次进入才会调用 获取市区级
          if (that.data.city_s.length == 0) {
            that.getCity(res.data.data[0].id);
          }
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //获取市信息 getCity
  getCity: function(provinceid) {
    var that = this;
    app.ajax({
      url: 'Common/Areas/areas',
      method: "POST",
      data: {
        parent_id: provinceid
      },
      success: function(res) {
        if (res.data.code == 1000) {
          that.setData({
            city_s: res.data.data
          });
          //重置区域信息 
          that.getArea(res.data.data[0].id);
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //获取区域信息 getArea
  getArea: function(cityid) {
    var that = this;
    app.ajax({
      url: 'Common/Areas/areas',
      method: "POST",
      data: {
        parent_id: cityid
      },
      success: function(res) {
        if (res.data.code == 1000) {
          that.setData({
            area_s: res.data.data
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //根据经纬度获取城市信息
  getCityLocation: function(latitude, longitude) {
    var that = this;
    //方法一：通过WebService API 地址逆解析
    // app.ajax({
    //   // url: 'https://api.map.baidu.com/geocoder/v2/?ak=' + that.data.ak_code + '&location=' + latitude + ',' + longitude + '&output=json',//百度地图api
    //   url: 'https://apis.map.qq.com/ws/geocoder/v1/?location='+latitude+','+longitude+'&key='+that.data.ak_code+'&get_poi=1',//腾讯地图api
    //   method:'GET',
    //   data: {},
    //   header: {
    //     'Content-Type': 'application/json'
    //   },
    //   success: function(res) {
    //     wx.hideLoading();
    //     //百度地图返回参数
    //     // that.getCityCode(res.data.result.addressComponent.province, res.data.result.addressComponent.city, res.data.result.addressComponent.district)
    //     //腾讯地图返回参数
    //     that.getCityCode(res.result.address_component.province, res.result.address_component.city, res.result.address_component.district)
    //     // 更新用户地址
    //     // that.updateAddress(res.data.result.addressComponent);
    //   },
    //   fail: function() {},

    // })
    // 方法二：通过微信小程序JavaScript SDK 地址逆解析
    MapWXsap.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function(res) {
      
    
        // 更新用户地址
        wx.setStorageSync('country', res.result.address_component.nation);
        wx.setStorageSync('province', res.result.address_component.province);
        wx.setStorageSync('city', res.result.address_component.city);
        wx.setStorageSync('area', res.result.address_component.district);
        address_component= res.result.address_component
        that.getCityCode(res.result.address_component.province, res.result.address_component.city, res.result.address_component.district)

      },
      fail: function(res) {
        //console.log(res);
      },
      complete: function(res) {}
    });
  },

  // 更新用户地址
  updateAddress: function(addr) {
    var that = this;
    app.ajax({
      url: 'User/User/editAddress',
      data: {
        country: addr.nation,
        province: addr.province,
        city: addr.city,
        area: addr.district,
        id: area_id_Info,
        address_is_update: 2
      },
      success: function(res) {
        //console.log('更新用户地址结果', res)
      }
    })
  },
  //更新用户地址
  updateTwoAddress: function(ad_dr) {
    var that = this;
    app.ajax({
      url: 'User/User/editAddress',
      data: {
        country: '中国',
        province: ad_dr[0],
        city: ad_dr[1],
        area: ad_dr[2],
        id: area_id_Info,
        address_is_update: 2
      },
      success: function(res) {
        //console.log('更新用户地址结果', res)
      }
    })
  },

  //根据地址查询地区code
  getCityCode: function(province, city, district) {
    var that = this;
    app.ajax({
      url: 'Common/Areas/getAreasCode',
      method: "POST",
      data: {
        province: province,
        city: city,
        area: district
      },
      success: function(res) {
        //console.log(res.data)
        if (res.data.code == 1000) {
          var areaInfo_name = []; //区域名称
          areaInfo_name.push(res.data.data.province_info.area_name);
          areaInfo_name.push(res.data.data.city_info.area_name);
          areaInfo_name.push(res.data.data.area_info.area_name);
          var area_id_Info_s = []; //区域id
          area_id_Info_s.push(res.data.data.province_info.id);
          area_id_Info_s.push(res.data.data.city_info.id);
          area_id_Info_s.push(res.data.data.area_info.id);
          wx.setStorage({ key: 'area_id', data: area_id_Info_s});
          wx.setStorage({
            key: 'areaInfo_name',
            data: areaInfo_name
          });
          codeInfo= res.data.data;
          that.setData({
            areaInfo_name: areaInfo_name,
            tdsinfo: res.data.data.tds_info.tds
          });
          area_id_Info= area_id_Info_s
         
          // that.setProDefault(res.data.data);
          load= true;
          that.setData({
            goods: [],
            load_show: false,
            page: 1
          });
          that.getGoodsList();
          if (wx.getStorageSync('phone')) {
            that.updateAddress(address_component);
          }
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //根据地址设置更换地址省的默认值
  setProDefault: function(info) {
    var that = this;
    var province_s = that.data.province_s;
    for (var i in province_s) {
      if (province_s[i].id == info.province_info.id) {
        var a = 'value_sel[0]';
        that.setData({
          [a]: parseInt(i)
        })
        app.ajax({
          url: 'Common/Areas/areas',
          method: "POST",
          data: {
            parent_id: province_s[i].id
          },
          success: function(res) {
            if (res.data.code == 1000) {
              // console.log(res.data.data);          
              that.setData({
                city_s: res.data.data
              });
              that.setCityDefault(info);
            } else {
              app.showToast(res.data.message);
            }
          }
        })
      }
    }

  },
  //根据地址设置更换地址市的默认值
  setCityDefault: function(info) {
    var that = this;
    var city_s = that.data.city_s;
    for (var i in city_s) {
      if (city_s[i].id == info.city_info.id) {
        var a = 'value_sel[1]';
        that.setData({
          [a]: parseInt(i)
        })
        app.ajax({
          url: 'Common/Areas/areas',
          method: "POST",
          data: {
            parent_id: city_s[i].id
          },
          success: function(res) {
            if (res.data.code == 1000) {
              // console.log(res.data.data);          
              that.setData({
                area_s: res.data.data
              });
              that.setAreaDefault(info);
            } else {
              app.showToast(res.data.message);
            }
          }
        })
        break;
      }
    }
  },
  //根据地址设置更换地址区的默认值
  setAreaDefault: function(info) {
    var that = this;
    var area_s = that.data.area_s;
    for (var i in area_s) {
      if (area_s[i].id == info.area_info.id) {
        var a = 'value_sel[2]';
        that.setData({
          [a]: parseInt(i)
        })
        break;
      }
    }
  },

  // .............................地址选择end
  //获取商品列表
  getGoodsList: function() {

    var that = this;

    var provice_code = area_id_Info[0];
    var city_code = area_id_Info[1];
    var area_code = area_id_Info[2];
    //console.log(page);
    var onTab=that.data.onTab;
    app.ajax({
      url: 'User/Equipment/index',
      method: "POST",
      data: {
        equipments_type_id: onTab,
        provice_code: provice_code,
        city_code: city_code,
        area_code: area_code,
        page: that.data.page,
        pageSize: _PAGESIZE
      },
      success: function(res) {
        wx.hideLoading();
        wx.stopPullDownRefresh()
        if (res.data.code == 1000) {

          var list = res.data.data.data;
          var goods = that.data.goods;

          goods = goods.concat(res.data.data.data)
          // list.forEach(function(v,k){
          //   goods.push(v);
          // })
          //是否需要加载更多
          var hasMore = true;
          if (res.data.data.data.length < _PAGESIZE) {
            hasMore = false;        
          }
          that.setData({
            hasMore: hasMore,
            loading: false,
            load_show: true,
            goods: goods
          })
          load= false;
        } else {
          if (that.data.page == 1) {
            that.setData({
              hasMore: false,
              loading: false,
              empty: true
            })
          } else {
            that.setData({
              hasMore: false,
              loading: false,
              empty: false
            })
          }
          app.showToast(res.data.message);
        }
      }
    })
  },
  //图片加载错误
  binderrorimg(e) {
    var index = e.currentTarget.dataset.errorindex,
      that = this,
      imgUrls = that.data.imgUrls;
    imgUrls[index].banner_image = '../../../images/none.png'
    that.setData({
      imgUrls: imgUrls
    })
  },
  binderrorlist(e) {
    var index = e.currentTarget.dataset.errorindex,
      that = this,
      goodsChange = that.data.goods;
    goodsChange[index].main_pic = '../../../images/none.png'
    that.setData({
      goods: goodsChange
    })
  },
  //外部链接
  outpage(e){
    var url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: '../../outpage/outpage?url=' + url,
    })
  },
  //选择Tab
  choseTab(e){
    var that=this;
    var on_tab = e.currentTarget.dataset.on_tab;
    if (on_tab == that.data.onTab){
        return false
      }
      that.setData({
        onTab: on_tab,
        goods: [],
        load_show: false,
        page: 1
      })
    load= true;
    that.getGoodsList();
  },
  //浏览记录
  shareLogHistory() {
    var that = this;
    app.ajax({
      url: 'User/Browse/browseLog',
      method: "POST",
      data: { browse_page: 'pages/shopping/shoppingHome/shoppingHome' },//1是邀请好友 2分享详情 
      success: function (res) {
        if (res.data.code = 1000) {
        } else {
        }
      }

    })
  },
  //获取分类列表
  getEquipmentstypeList() {
    var that = this;
    app.ajax({
      url: 'User/Equipmentstype/getEquipmentstypeList',
      method: "POST",
      data: { page: 1, pageSize: 100, pid:0 },//1是邀请好友 2分享详情 
      success: function (res) {
        if (res.data.code = 1000) {
            that.setData({
              onTab:res.data.data[0].id,
              tablelist:res.data.data
            })
        } else {

        }
        that.getUserAuthInfo();//获取用户授权信息并且查询商品列表
      }

    })
  },

})